import { withPluginApi } from 'discourse/lib/plugin-api';

// Helper: extract topic model and details from topic controller
function extractTopicData(topicController) {
  let topicModel = null;
  let details = null;
  try {
    if (topicController && typeof topicController.get === 'function') {
      topicModel = topicController.get('model');
      // if top-level model doesn't expose is_replied, try details
      if (!topicModel || (typeof topicModel.get === 'function' ? typeof topicModel.get('is_replied') === 'undefined' : typeof topicModel.is_replied === 'undefined')) {
        details = topicController.get('model.details');
      }
    } else if (topicController && topicController.model) {
      topicModel = topicController.model;
      details = topicController.model.details;
    }
  } catch (e) {
    topicModel = null;
    details = null;
  }
  return { topicModel, details };
}

// Helper: compute is_replied from multiple possible shapes
function computeIsReplied(topicModel, details) {
  let isReplied = false;
  try {
    if (topicModel) {
      if (typeof topicModel.get === 'function') {
        const v = topicModel.get('is_replied');
        if (typeof v !== 'undefined' && v !== null) {
          isReplied = !!v;
        } else {
          const v2 = topicModel.get('isReplied');
          if (typeof v2 !== 'undefined' && v2 !== null) {
            isReplied = !!v2;
          }
        }
      } else {
        if (typeof topicModel.is_replied !== 'undefined' && topicModel.is_replied !== null) {
          isReplied = !!topicModel.is_replied;
        } else if (typeof topicModel.isReplied !== 'undefined' && topicModel.isReplied !== null) {
          isReplied = !!topicModel.isReplied;
        }
      }
    }

    if (!isReplied && details) {
      if (typeof details.get === 'function') {
        const dv = details.get('is_replied');
        isReplied = !!dv;
      } else if (typeof details.is_replied !== 'undefined') {
        isReplied = !!details.is_replied;
      }
    }
  } catch (e) {
    isReplied = false;
  }
  return isReplied;
}

function initializeWithApi(api) {
  const currentUser = api.getCurrentUser();
  console.debug('[PLUGIN discourse-reply-required] currentUser:', currentUser);

  $.fn.actionRequired = function(options) {
    //console.debug('[PLUGIN discourse-reply-required] actionRequired called, options=', options, 'elements=', this);
    const noticeType = '内容';
    const actionType = options === 'reply' ? '回复' : '登录';
    const noticeText = `${actionType}后点击刷新可查看${noticeType}`;

    const topicController = api.container && api.container.lookup ? api.container.lookup('controller:topic') : null;
    const { topicModel, details } = extractTopicData(topicController);
    const isRepliedState = computeIsReplied(topicModel, details);
    //console.debug('[PLUGIN discourse-reply-required] topicModel:', topicModel, 'details:', details, 'isRepliedState:', isRepliedState);

    if (options === 'reply') { // reply action
      //console.debug('[PLUGIN discourse-reply-required] reply branch entered; isRepliedState=', isRepliedState);
      const isStaff = currentUser && (typeof currentUser.get === 'function' ? currentUser.get('staff') : currentUser.staff);
      if (isRepliedState || isStaff) {
        //console.debug('[PLUGIN discourse-reply-required] user can view content (replied or staff)');
        this.show(true);
      } else {
        //console.info('[PLUGIN discourse-reply-required] user has NOT replied and is not staff; applying reply-required replacement');
        // If the element is a <details>, preserve the <summary> and replace everything after it
        if (this.is('details')) {
          this.each(function() {
            const $details = $(this);
            const $summary = $details.children('summary').first();
            //console.debug('[PLUGIN discourse-reply-required] processing <details> element, summary=', $summary);
            // remove all children except summary
            $details.children().not($summary).remove();
            // append notice
            $details.append($(`<p class="reply-required-notice">${noticeText}</p>`));
            //console.debug('[PLUGIN discourse-reply-required] appended notice to <details>:', noticeText);
          });
        } else {
          //console.debug('[PLUGIN discourse-reply-required] replacing non-<details> element with notice');
          this.show(false).replaceWith(`<p class="reply-required-notice">${noticeText}</p>`);
        }
      }

        if (currentUser) {
          // Simplified behavior: clicking the notice just reloads the page so
          // any new replies (made via the composer) are reflected.
          $('body').off('click.ReplyRequired').on('click.ReplyRequired', '.reply-required-notice', function () {
            //console.debug('[PLUGIN discourse-reply-required] reply-required notice clicked: reloading page');
            window.location.reload(false);
          });
        }
    } else { // login action
      //console.debug('[PLUGIN discourse-reply-required] login branch entered');
      if (currentUser) {
        this.show(true);
      } else {
        //console.info('[PLUGIN discourse-reply-required] user not logged in; replacing element with login-required notice');
        this.show(false).replaceWith(`<p class="login-required-notice">${noticeText}</p>`);
      }
    }
  };


  /* Markdown baking */
  api.decorateCooked(($elem, model) => {
    console.debug('[PLUGIN discourse-reply-required] decorateCooked called for element:', $elem, 'model:', model);
    // apply only for first post in stream or when model indicates firstPost
    let isFirstPost = false;
    if (model) {
      if (typeof model.getModel === 'function') {
        const m = model.getModel();
        if (m) {
          isFirstPost = (typeof m.get === 'function') ? m.get('firstPost') : !!m.firstPost;
        }
      } else {
        isFirstPost = !!model.firstPost;
      }
    }

    if (model && (isFirstPost || typeof model.getModel !== 'function')) {
      //console.debug('[PLUGIN discourse-reply-required] applying actionRequired to cooked content');

      // New behavior: detect <details> elements whose <summary> matches the
      // Chinese placeholder used for hidden/reply-required content and
      // apply the existing actionRequired('reply') behavior to them.
      // This covers cases where the first post's cooked HTML is just a
      // <details> element (no surrounding .reply-required wrapper).
      $elem.find('details').each(function() {
        const $details = $(this);
        const $summary = $details.children('summary').first();
        if (!$summary || !$summary.length) { return; }
        const summaryText = $summary.text().trim();
        if (summaryText === '回复本帖以查看隐藏内容') {
          //console.debug('[PLUGIN discourse-reply-required] found matching <details>; delegating to actionRequired', $details);
          // Delegate to the existing actionRequired handler so the notice
          // text and click behavior remain consistent.
          $details.actionRequired('reply');
        }
      });

    }
  });

}

export default {
  name: 'discourse-reply-required',
  initialize() {
    withPluginApi('0.0.1', initializeWithApi);
  }
};
